import {Effect, Reducer} from 'umi';
import {
  queryRoleDataList,
  createRole,
  queryDataRoleDetail,
  queryRoleAllList,
  bindDataRole,
  queryUserRole
} from '@/services/information';

export interface dataRoleModelState {
  dataRoleList: Array<any>
  RoleDetail: Array<any>
  RoleAllList: Array<any>
  userRole: Array<any>
  userRoleLoading: boolean
}

export interface DataRoleModelType {
  namespace: 'dataRole';
  state: dataRoleModelState;
  effects: {
    fetchRoleList: Effect;
    storageRoleData: Effect;
    fetchRoleDetail: Effect;
    fetchRoleAllList: Effect;
    saveRoleDataBind: Effect;
    fetchUserRole: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const dataRoleModel: DataRoleModelType = {
  namespace: 'dataRole',

  state: {
    dataRoleList: [],
    RoleDetail: [],
    RoleAllList: [],
    userRole: [],
    userRoleLoading: false
  },

  effects: {
    // 获取表格数据列表
    * fetchRoleList(_, {call, put}) {
      const response = yield call(queryRoleDataList);
      yield put({
        type: 'save',
        payload: {dataRoleList: response.payload},
      });
    },

    // 存储导入数据
    * storageRoleData({payload, callback}, {call}) {
      const response = yield call(createRole, payload);

      if (callback) callback(response);
    },

    // 根据数据角色唯一no获取数据角色明细
    * fetchRoleDetail({payload, callback}, {call, put}) {
      const response = yield call(queryDataRoleDetail, payload);

      yield put({
        type: 'save',
        payload: {RoleDetail: response.payload},
      });

      if (callback) callback(response);

    },

    // 获取所有数据角色(包含明细)
    * fetchRoleAllList(_, {call, put}) {
      const response = yield call(queryRoleAllList);
      yield put({
        type: 'save',
        payload: {RoleAllList: response.payload},
      });
    },

    // 用户绑定数据角色
    * saveRoleDataBind({payload, callback}, {call}) {
      const response = yield call(bindDataRole, payload);

      if (callback) callback(response);
    },

    // 用户已绑定的数据角色
    * fetchUserRole({payload}, {call, put}) {
      yield put({
        type: 'save',
        payload: {userRoleLoading: true},
      });
      const response = yield call(queryUserRole, payload);
      yield put({
        type: 'save',
        payload: {userRole: response.payload, userRoleLoading: false},
      });
    },

  },

  reducers: {
    save(state, {payload}) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};

export default dataRoleModel;
